﻿using DAL.DBManagers;
using DAL.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class Login : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        HttpCookie userAuthCookie = Request.Cookies["userAuth"];
        if (userAuthCookie != null)
        {
            usname.Value = userAuthCookie["username"];
            uspw.Value = userAuthCookie["password"];
            btnSubmit_Click(null, null);
        }
    }

    protected void btnSubmit_Click(object sender, EventArgs e)
    {
        using (UsersManager manager = new UsersManager())
        {
            UserHelper user;

            if (manager.Authentifacation(out user, usname.Value, HelperService.GetMd5Hash(uspw.Value)))
            {
                if (remember.Checked)
                {
                    HttpCookie cookie = (Request.Cookies["userAuth"] ?? new HttpCookie("userAuth"));
                    cookie["username"] = usname.Value;
                    cookie["password"] = uspw.Value;
                    Response.Cookies.Set(cookie);
                }
                Session["User"] = user;
                invalidPassword.Visible = false;
                Response.Redirect("default.aspx");
            }
            else if (e == null && sender == null)
            {
                Request.Cookies.Remove("userAuth");
                Response.Redirect("login.aspx");
                invalidPassword.Visible = false;
            }
            else
            {
                invalidPassword.Visible = true;
            }
        }
    }


}